import { useState, useEffect } from 'react';
import {
  DndContext,
  closestCenter,
  DragOverlay,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  rectSortingStrategy,
} from '@dnd-kit/sortable';

import { SortableItem } from './SortableItem';
import { restrictToWindowEdges } from '@dnd-kit/modifiers';

function App() {
  const [items, setItems] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]);
  const [activeId, setActiveId] = useState(null); // 用于存储当前拖动的项
  // 传感器
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  useEffect(() => {
    console.log("items交换位置or数据变化,提交", items);
  }, [items]);

  return (
    <>
      <DndContext
        modifiers={[restrictToWindowEdges]}
        sensors={sensors}
        collisionDetection={closestCenter}
        onDragStart={handleDragStart}
        onDragEnd={handleDragEnd}
      >
        <SortableContext
          items={items}
          strategy={rectSortingStrategy}
        >
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px' }}>
            {items.map(id => {
              if (id === activeId) {
                return <SortableItem key={id} id={id} style={{ backgroundColor: '#EFF0FA',border: '1px dashed blue' }}></SortableItem>
              }
              return (
                <SortableItem key={id} id={id} style={{ backgroundColor: '#FBE8E8' }}>
                  {id}
                </SortableItem>
              )
            })}
          </div>
        </SortableContext>
        <DragOverlay>
          {activeId ? <SortableItem id={activeId}>{activeId}</SortableItem> : null}
        </DragOverlay>
      </DndContext>
    </>
  );

  function handleDragStart(event) {
    setActiveId(event.active.id); // 设置当前拖动的项
  }

  function handleDragEnd(event) {
    const { active, over } = event;

    if (active.id !== over.id) {
      setItems((items) => {
        const oldIndex = items.indexOf(active.id);
        const newIndex = items.indexOf(over.id);
        return swap(items, oldIndex, newIndex);
      });
    }
    setActiveId(null); // 清除当前拖动的项
  }
  function swap(items, oldIndex, newIndex) {
    const newItems = [...items];
    newItems[oldIndex] = items[newIndex];
    newItems[newIndex] = items[oldIndex];
    return newItems;
  }
}

export default App;